import { createRouter, createWebHistory } from 'vue-router'

import HomePage from '../views/HomePage.vue'
import NotFound from '../views/NotFound.vue'

const routes = [
  {
    path: '/',
    name: 'Home',
    component: HomePage
  },
  {
    path: '/posts',
    name: 'Posts',
    component: () => import('../views/PostsPage.vue'),
  },
  {
    path: '/posts/:id',
    name: 'PostDetail',
    component: () => import('../views/PostDetail.vue')
  },
  {
    path: '/project/:id',
    name: 'ProjectDetail',
    component: () => import('../views/ProjectDetail.vue')
  }
  ,{
    path: '/user/:id',
    name: 'UserInfo',
    component: () => import('../views/UserInfo.vue')
  },
  {
    path: '/tool',
    name: 'Tool',
    component: () => import('../views/Tool.vue')
  },
  {
    path: '/project',
    name: 'Project',
    component: () => import('../views/Project.vue')
  },
  {
    path: '/softwareCopyright',
    name: 'SoftwareCopyright',
    component: () => import('../views/SoftwareCopyright.vue')
  },
  {
    path: '/tags',
    name: 'Tags',
    component: () => import('../views/TagsPage.vue')
  },
  {
    path: '/service',
    name: 'Service',
    component: () => import('../views/Service.vue')
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('../views/AboutPage.vue')
  },
  {
    path: '/advanced-search',
    name: 'AdvancedSearch',
    component: () => import('../components/AdvancedSearch.vue')
  },
  {
    path: '/posts/new',
    name: 'NewPost',
    component: () => import('../views/PostEditPage.vue')
  },
  {
    path: '/posts/:id/edit',
    name: 'EditPost',
    component: () => import('../views/PostEditPage.vue')
  },
  {
    path: '/:pathMatch(.*)*',
    name: 'NotFound',
    component: NotFound
  }
]

const router = createRouter({
  history: createWebHistory('/'),
  routes,
  scrollBehavior() {
    return { top: 0 }
  }
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 获取本地存储的token
  const token = localStorage.getItem('token')
  
  // 如果目标路由是 /posts/new 且用户未登录
  if (to.path === '/posts/new' && !token) {
    ElMessage({
      message: '请先登录',
      type: 'warning',
    })
    // 阻止路由跳转
    next(false)
  } 
  // 如果用户未登录且尝试访问用户个人中心
  else if (to.path.startsWith('/user/') && !token) {
    // 重定向到首页
    next('/')
  } else {
    // 允许导航
    next()
  }
})

export default router
